//
//  WmcCancellationFeedbackVM.swift
//  YPWatermarkCamera
//
//  Created by 马涛 on 2022/6/21.
//

import Foundation
import Moya
import YPNetwork
import RxSwift

class WmcCancellationFeedbackVM: WmcBaseVM {

    typealias Task = (data: Data,fileName: String)
    
    /// 注销原因
    var reason: String?
    /// 图片
    var imgs: [UIImage]?
    /// 上传成功之后  返回的图片地址
    var imgUrls: [String]?
    /// 验证码
    var code: String?
    /// 手机号
    var tel: String = WmcLoginManager.shared.wmcAccountModel?.phone ?? ""
    
    let cancelResult: BehaviorRelay<WmcCancellationResultModel?> = .init(value: nil)
    
    /// 上传图片
    /// - Returns: description
    private func uploadImgs() -> Observable<[String]> {
        guard let imgs = imgs,imgs.count > 0 else {
            return RxSwift.Observable.create { ob in
                ob.onNext([])
                return Disposables.create {}
            }
        }
        var tasks: [Task] = []
        imgs.forEach { image in
            if let imgData = image.yp.jpegData(compressed: 0.5) {
                let key = self.createObjectKey()
                tasks.append((imgData,key))
            }
        }
        return RxSwift.Observable.create { ob in
            YPNetworkUploadRequest.multiUploadTasks(tasks, success: { response in
                var imgUrls: [String] = []
                response.forEach { item in
                    imgUrls.append(item.imageName)
                }
                ob.onNext(imgUrls)
            }, failure: { error in
                WmcHudManager.toast("上传失败")
                ob.onError(error)
            })
            return Disposables.create { }
        }
    }
    
    /// 构建参数
    /// - Parameter imgUrls: imgUrls description
    /// - Returns: description
    private func constructParams(imgUrls: [String]) -> [String: Any] {
        var params: [String: Any] = [String: Any]()
        params["note"] = self.reason ?? ""
        params["clearance_agreement"] = 1
        if imgUrls.count > 0 {
            var index = 0
            imgUrls.forEach {
                params["images[\(index)]"] = $0
                index += 1
            }
        }
        if let c = code {
            params["confirm"] = 1
            params["code"] = c
            params["tel"] = tel
        }
        return params
    }
    
    /// 注销账号
    /// - Parameter imgUrls: imgUrls description
    /// - Returns: description
    private func cancellationAccount(imgUrls: [String]) -> Observable<WmcCancellationResultModel> {
        return WmcNetwork.request(.general(method: .post, path: "/user/member/closeAccount", params: self.constructParams(imgUrls: imgUrls))).mapModel(WmcCancellationResultModel.self, throwErrorEnable: false, customThrowError: nil)
    }
    
    /// 注销账号
    /// - Returns: description
    func cancelAccount() -> Void {
        self.uploadImgs().flatMap(self.cancellationAccount(imgUrls:)).subscribe {[weak self] result in
            guard let weakSelf = self else { return }
            weakSelf.cancelResult.accept(result)
        } onError: { error in
            WmcHudManager.toast(error)
        }.disposed(by: rx.disposeBag)
    }
    
    
    /// 阿里云上传参数  key
    /// - Returns: description
    private func createObjectKey() -> String {
        let date = WmcDateManager.shared.networkDate.value ?? Date()
        let imgName = createImgName(date: date)
        let dateFolderName = date.yp.string("yyyyMMdd")
        let objectKey = "ios/\(dateFolderName)/\(imgName)"
        return objectKey
    }

    // Private
    private func createImgName(date: Date) -> String {
        let arcStr: String = date.timeIntervalSince1970.yp.string.yp.replacing(".", with: "_")
        guard let account: WmcAccountModel = WmcLoginManager.shared.wmcAccountModel else { return "\(arcStr).jpeg" }
        let uid = account.memberId
        return "\(arcStr)\(uid).png"
    }
    
    /// 判断是否含有汉字
    private func includeChinese() -> Bool {
        var temp = ""
        if let t = reason {
            temp = t
        }
        for (_, item) in temp.enumerated() {
            if ("\u{4E00}" <= item && item <= "\u{9FA5}") {
                return true
            }
        }
        return false
    }
    
    /// 判断输入有效性
    /// - Parameter reason: reason description
    /// - Returns: description
    func isInputValidate() -> Bool {
        var temp = ""
        if let t = reason {
            temp = t
        }
        return self.includeChinese() && temp.count >= 15 && temp.count <= 300
    }
}
